package com.iot.manager.ui.activities;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.camera.core.AspectRatio;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraControl;
import androidx.camera.core.CameraInfo;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ExperimentalGetImage;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.core.resolutionselector.ResolutionSelector;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.iot.manager.R;
import com.iot.manager.data.models.Device;
import com.iot.manager.utils.DeviceWifiManager;
import com.iot.manager.utils.UdpManager;

import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class QRScannerActivity extends AppCompatActivity {
    private static final String TAG = "QRScannerActivity";
    private static final int REQUEST_CAMERA_PERMISSION = 10;
    private static final String[] REQUIRED_PERMISSIONS = new String[]{"android.permission.CAMERA"};

    private PreviewView previewView;
    private ExecutorService cameraExecutor;
    private boolean isScanning = false;
    private ImageAnalysis imageAnalysis;
    private Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qr_scanner);

        // 设置屏幕方向
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // 初始化工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("扫描二维码");
        }

        // 初始化视图
        previewView = findViewById(R.id.previewView);
        MaterialButton btnFlash = findViewById(R.id.btn_flash);

        // 初始化相机执行器
        cameraExecutor = Executors.newSingleThreadExecutor();

        // 检查相机权限
        if (allPermissionsGranted()) {
            startCamera();
        } else {
            ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CAMERA_PERMISSION);
        }

        // 设置闪光灯按钮点击事件
        btnFlash.setOnClickListener(v -> toggleFlash());
    }

    private void startCamera() {
        ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);

        cameraProviderFuture.addListener(() -> {
            try {
                ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
                bindPreview(cameraProvider);
            } catch (ExecutionException | InterruptedException e) {
                Log.e(TAG, "Error starting camera", e);
                Toast.makeText(this, "启动相机失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                finish();
            }
        }, ContextCompat.getMainExecutor(this));
    }

    private void bindPreview(@NonNull ProcessCameraProvider cameraProvider) {
        Preview preview = new Preview.Builder().build();
        preview.setSurfaceProvider(previewView.getSurfaceProvider());

        // 创建图像分析用例
        imageAnalysis = new ImageAnalysis.Builder()
                .setTargetResolution(new android.util.Size(1280, 720))
                .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                .build();

        imageAnalysis.setAnalyzer(cameraExecutor, new QRCodeAnalyzer());

        CameraSelector cameraSelector = new CameraSelector.Builder()
                .requireLensFacing(CameraSelector.LENS_FACING_BACK)
                .build();

        try {
            cameraProvider.unbindAll();
            camera = cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
        } catch (Exception e) {
            Log.e(TAG, "Use case binding failed", e);
            Toast.makeText(this, "相机绑定失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private class QRCodeAnalyzer implements ImageAnalysis.Analyzer {
        private final MultiFormatReader reader = new MultiFormatReader();
        private final Map<DecodeHintType, Object> hints = new EnumMap<>(DecodeHintType.class);

        public QRCodeAnalyzer() {
            hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
            hints.put(DecodeHintType.POSSIBLE_FORMATS, Collections.singletonList(BarcodeFormat.QR_CODE));
        }

        @OptIn(markerClass = ExperimentalGetImage.class)
        @Override
        public void analyze(@NonNull ImageProxy image) {
            if (isScanning) {
                image.close();
                return;
            }

            try {
                Image mediaImage = image.getImage();
                if (mediaImage != null) {
                    // 将图像转换为灰度图
                    byte[] data = new byte[mediaImage.getWidth() * mediaImage.getHeight()];
                    int[] pixels = new int[mediaImage.getWidth() * mediaImage.getHeight()];
                    mediaImage.getPlanes()[0].getBuffer().get(data);

                    // 创建二进制位图
                    PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(
                            data,
                            mediaImage.getWidth(),
                            mediaImage.getHeight(),
                            0,
                            0,
                            mediaImage.getWidth(),
                            mediaImage.getHeight(),
                            false
                    );

                    BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));

                    try {
                        Result result = reader.decode(binaryBitmap, hints);
                        if (result != null) {
                            isScanning = true;
                            String qrContent = result.getText();
                            Log.d(TAG, "QR Code detected: " + qrContent);

                            // 在主线程中处理结果
                            runOnUiThread(() -> {
                                // 验证二维码格式
                                String[] parts = qrContent.split("\\|");
                                if (parts.length == 5) {
                                    // 返回扫码结果
                                    Intent resultIntent = new Intent();
                                    resultIntent.putExtra("qr_content", qrContent);
                                    setResult(RESULT_OK, resultIntent);
                                    finish();
                                } else {
                                    Toast.makeText(QRScannerActivity.this, "无效的二维码格式", Toast.LENGTH_SHORT).show();
                                    isScanning = false;
                                }
                            });
                        }
                    } catch (NotFoundException e) {
                        // 没有找到二维码，继续扫描
                    } catch (Exception e) {
                        Log.e(TAG, "Error decoding QR code", e);
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "Error analyzing image", e);
            } finally {
                image.close();
            }
        }
    }

    private void toggleFlash() {
        if (isScanning || camera == null) return;
        try {
            CameraControl cameraControl = camera.getCameraControl();
            boolean isTorchOn = camera.getCameraInfo().getTorchState().getValue() == 1;
            cameraControl.enableTorch(!isTorchOn);
        } catch (Exception e) {
            Log.e(TAG, "Error toggling flash", e);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (allPermissionsGranted()) {
            startCamera();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        cameraExecutor.shutdown();
    }

    private boolean allPermissionsGranted() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CAMERA_PERMISSION) {
            if (allPermissionsGranted()) {
                startCamera();
            } else {
                Toast.makeText(this, "需要相机权限才能使用扫码功能", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
} 